<template>
  <div class="h-full">
    <n-card class="h-full shadow-sm rounded-16px">
      <n-form class="w-full h-40px" size="small" inline>
        <n-form-item label="日期:" label-placement="left">
          <n-date-picker
            v-model:value="range"
            type="datetimerange"
            clearable
            :default-time="['00:00:00', '00:00:00']"
          />
        </n-form-item>
        <n-form-item label="车间:" label-placement="left" style="width: 200px">
          <n-select
            v-model:value="selectedAreas"
            clearable
            multiple
            label-field="areaname"
            value-field="areaname"
            :options="areas"
          />
        </n-form-item>
        <n-form-item label="料号:" label-placement="left">
          <n-input v-model:value="selectedProductspecNames" type="text" placeholder="模糊查询" />
        </n-form-item>
        <n-form-item label="生产订单:" label-placement="left">
          <n-input v-model:value="selectedProductRequest" type="text" placeholder="模糊查询" />
        </n-form-item>
        <n-form-item label="工序:" label-placement="left" style="width: 200px">
          <n-select
            v-model:value="selectedProcessoperationNames"
            multiple
            clearable
            :options="processOperations"
            :render-label="poRenderLabel"
          />
        </n-form-item>
        <n-form-item label="" label-placement="left">
          <n-button type="primary" :on-click="getDailyReport">
            <template #icon><icon-mdi-map-search-outline /></template>
            查询
          </n-button>
        </n-form-item>
      </n-form>
      <!--n-collapse>
        <n-collapse-item title="更多筛选" name="1">
          <n-form class="w-full" size="small" inline>
            <n-form-item label="型号:" label-placement="left" style="width: 200px">
              <n-select v-model:value="selectedModelTypes" multiple clearable :options="modelTypes" />
            </n-form-item>
            <n-form-item label="生产订单:" label-placement="left" style="width: 240px">
              <n-select
                v-model:value="selectedProductRequests"
                multiple
                clearable
                filterable
                :options="productRequests"
              />
            </n-form-item>
            <n-form-item label="工单类型:" label-placement="left" style="width: 200px">
              <n-select v-model:value="selectedLotTypes" clearable multiple :options="lotTypes" />
            </n-form-item>
            <n-form-item label="工单类型1:" label-placement="left" style="width: 200px">
              <n-select v-model:value="selectedPanelTypes" multiple clearable :options="panelTypes" />
            </n-form-item>
          </n-form>
        </n-collapse-item>
      </！n-collapse-->
      <vxe-grid v-bind="dailyOptions">
        <template #top>
          <div class="alert-message">
            总合格率：
            <span style="color: green; font-weight: 800">
              {{ totalYield }}
            </span>
          </div>
        </template>
      </vxe-grid>
    </n-card>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue';
import type { SelectOption } from 'naive-ui';
import dayjs from 'dayjs';
import type { VxeGridProps } from 'vxe-table';
import {
  fetchAreaList,
  fetchModelType,
  fetchProductSpecAll,
  fetchProcessopetationspec,
  fetchLotType,
  fetchPanelType,
  fetchProductRequestAll,
  fetchEnumvalue,
  fetchDailyReportDataV2
} from '@/service/api';

const range = ref<[number, number]>([dayjs().startOf('month').valueOf(), Date.now()]);

const areas = ref<Factory.Area[]>([]);
const modelTypes = ref<Array<SelectOption>>([]);
const productSpecs = ref<Array<SelectOption>>([]);
const processOperations = ref<Array<SelectOption>>([]);
const lotTypes = ref<Array<SelectOption>>([]);
const panelTypes = ref<Array<SelectOption>>([]);
const productRequests = ref<Array<SelectOption>>([]);

const selectedAreas = ref([]);
const defectCodes = ref([]);
const selectedProductspecNames = ref('');
const selectedProductRequest = ref('');
const selectedProcessoperationNames = ref([]);

const getAreaList = async () => {
  const result = await fetchAreaList();
  if (result.data) {
    areas.value = result.data;
  }
};

const getModelTypAll = async () => {
  const result = await fetchModelType();
  if (result.data) {
    const modelTypeList: Array<SelectOption> = [];
    result.data.forEach(element => {
      const temp: SelectOption = {
        label: element,
        value: element
      };
      modelTypeList.push(temp);
    });
    modelTypes.value = modelTypeList;
  }
};

const getProductSpec = async () => {
  const result = await fetchProductSpecAll();
  if (result.data) {
    const productSpecList: Array<SelectOption> = [];
    result.data.forEach(element => {
      const temp: SelectOption = {
        label: element,
        value: element
      };
      productSpecList.push(temp);
    });
    productSpecs.value = productSpecList;
  }
};

const getProductRequest = async () => {
  const result = await fetchProductRequestAll();
  if (result.data) {
    const productRequestList: Array<SelectOption> = [];
    result.data.forEach(element => {
      const temp: SelectOption = {
        label: element,
        value: element
      };
      productRequestList.push(temp);
    });
    productRequests.value = productRequestList;
  }
};
const getProcessoperationSpec = async () => {
  const result = await fetchProcessopetationspec();
  if (result.data) {
    const processoperationSpecList: Array<SelectOption> = [];
    result.data.forEach(element => {
      const temp: SelectOption = {
        label: element.description,
        value: element.processoperationname
      };
      processoperationSpecList.push(temp);
    });
    processOperations.value = processoperationSpecList;
  }
};

const getLotType = async () => {
  const result = await fetchLotType();
  if (result.data) {
    const productSpecList: Array<SelectOption> = [];
    result.data.forEach(element => {
      const temp: SelectOption = {
        label: element.enumvalue,
        value: element.enumvalue
      };
      productSpecList.push(temp);
    });
    lotTypes.value = productSpecList;
  }
};

const getPanelType = async () => {
  const result = await fetchPanelType();
  if (result.data) {
    const productSpecList: Array<SelectOption> = [];
    result.data.forEach(element => {
      const temp: SelectOption = {
        label: element.enumvalue,
        value: element.enumvalue
      };
      productSpecList.push(temp);
    });
    panelTypes.value = productSpecList;
  }
};

const getDefectCode = async () => {
  const result = await fetchEnumvalue('DEFECT_CODE');
  if (result.data) {
    defectCodes.value = result.data;
  }
};
onMounted(async () => {
  getAreaList();
  getModelTypAll();
  getProductSpec();
  getProductRequest();
  getProcessoperationSpec();
  getLotType();
  getPanelType();
  getDefectCode();
});

const totalYield = ref('');

const sumNum = (list: any[], field: string) => {
  let count = 0;
  list.forEach(item => {
    count += Number(item[field]);
  });
  return count;
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const yieldNum = (list: any[], field: string) => {
  let totalIn = 0;
  let totalOut = 0;
  list.forEach(item => {
    totalIn += Number(item.INQTY);
    totalOut += Number(item.OUTPUT);
  });
  totalYield.value = `${((totalOut / totalIn) * 100).toFixed(2)}%`;
  return `${((totalOut / totalIn) * 100).toFixed(2)}%`;
};

// eslint-disable-next-line @typescript-eslint/no-unused-vars
const countNum = (list: any[], field: string) => {
  return `${list.length} 笔`;
};

const dailyOptions = reactive<VxeGridProps>({
  border: true,
  // height: 300,
  size: 'mini',
  height: 560,
  showFooter: true,
  align: null,
  columnConfig: {
    resizable: true
  },
  columns: [
    {
      field: 'LOTTYPE',
      title: '工单类别',
      width: '110px',
      sortable: true,
      filters: [
        { label: '桔红色工单', value: '桔红色工单' },
        { label: '淡蓝色工单', value: '淡蓝色工单' },
        { label: '深蓝色工单', value: '深蓝色工单' },
        { label: '黄色工单', value: '黄色工单' },
        { label: '粉红色工单', value: '粉红色工单' },
        { label: '红色工单', value: '红色工单' },
        { label: '绿色工单', value: '绿色工单' },
        { label: '白色工单', value: '白色工单' }
      ]
    },
    {
      field: 'PANELTYPE',
      title: '工单类别1',
      width: '120px',
      sortable: true,
      filters: [
        { label: '普通单', value: '普通单' },
        { label: '二等品单', value: '二等品单' },
        { label: '再加工单', value: '再加工单' },
        { label: '分单', value: '分单' },
        { label: '合单', value: '合单' },
        { label: '在制转单', value: '在制转单' },
        { label: '返修基座单', value: '返修基座单' },
        { label: '测片单', value: '测片单' },
        { label: '特采单', value: '特采单' },
        { label: '试验单', value: '试验单' },
        { label: '边缘片单', value: '边缘片单' },
        { label: '工单转单', value: '工单转单' }
      ]
    },
    { field: 'EVENTTIME', sortable: true, title: '过账时间', width: '150px' },
    {
      field: 'OLDAREANAME',
      title: '前道车间',
      width: '120px',
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'AREANAME',
      title: '车间',
      sortable: true,
      width: '110px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MACHINENAME',
      title: '设备',
      sortable: true,
      width: '100px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PROCESSOPERATIONNAME',
      title: '工序代号',
      sortable: true,
      width: '120px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'DESCRIPTION',
      title: '工序名称',
      sortable: true,
      width: '120px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'LOTNAME',
      title: '工单号',
      sortable: true,
      width: '150px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'MODELTYPE',
      title: '型号',
      sortable: true,
      width: '90px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PRODUCTSPECNAME',
      title: '成品料号',
      sortable: true,
      width: '200px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'TARGET',
      title: '测试FL值',
      sortable: true,
      width: '120px',
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    {
      field: 'PRODUCTREQUESTNAME',
      title: '生产订单',
      width: '150px',
      sortable: true,
      filters: [{ data: { vals: [], sVal: '' } }],
      filterRender: { name: 'FilterContent' }
    },
    { field: 'INQTY', sortable: true, title: '投入', width: '80px' },
    { field: 'OUTPUT', sortable: true, title: '产出', width: '80px' },
    {
      field: 'YIELD',
      sortable: true,
      sortType: 'number',
      title: '合格率',
      width: '80px',
      formatter({ cellValue }) {
        return cellValue === 0 ? '' : `${cellValue}%`;
      }
    },
    { field: 'NGNAME1', sortable: true, title: '不良名称1', width: '100px' },
    { field: 'NGQTY1', sortable: true, title: '不良数量1', width: '100px' },
    { field: 'NGNAME2', sortable: true, title: '不良名称2', width: '100px' },
    { field: 'NGQTY2', sortable: true, title: '不良数量2', width: '100px' },
    { field: 'NGNAME3', sortable: true, title: '不良名称3', width: '100px' },

    { field: 'NGQTY3', sortable: true, title: '不良数量3', width: '100px' },
    { field: 'NGNAME4', sortable: true, title: '不良名称4', width: '100px' },
    { field: 'NGQTY4', sortable: true, title: '不良数量4', width: '100px' },
    {
      field: 'EVENTUSER',
      sortable: true,
      title: '操作人员',
      width: '150px',
      filters: [{ data: '' }],
      filterRender: { name: 'FilterInput' }
    }
  ],
  toolbarConfig: {
    buttons: [],
    export: true,
    print: true,
    // zoom: true,
    custom: true
  },
  data: [],
  mergeCells: [],
  footerMethod({ columns, data }) {
    return [
      columns.map((column, columnIndex) => {
        if (columnIndex === 0) {
          return 'Σ总计';
        }
        if (column.field === 'LOTNAME') {
          return countNum(data, column.property);
        }
        if (
          column.field === 'INQTY' ||
          column.field === 'OUTPUT' ||
          column.field === 'NGQTY1' ||
          column.field === 'NGQTY2' ||
          column.field === 'NGQTY3' ||
          column.field === 'NGQTY4'
        ) {
          return sumNum(data, column.property);
        }
        if (column.field === 'YIELD') {
          return yieldNum(data, column.property);
        }
        return '';
      })
    ];
  },
  exportConfig: {
    remote: false,
    types: ['xlsx'],
    modes: ['current', 'selected', 'all']
  }
});

const poRenderLabel = (option: SelectOption) => {
  return `${option.value} - ${option.label}`;
};

const getDailyReport = async () => {
  const result = await fetchDailyReportDataV2(
    dayjs(range.value[0]).format('YYYYMMDDHHmmss'),
    dayjs(range.value[1]).format('YYYYMMDDHHmmss'),
    selectedAreas.value.join(','),
    selectedProductspecNames.value,
    selectedProcessoperationNames.value.join(','),
    selectedProductRequest.value
  );
  if (result.data) {
    // eslint-disable-next-line no-plusplus
    for (let i = 0; i < result.data.length; ++i) {
      // eslint-disable-next-line no-plusplus
      for (let j = 0; j < defectCodes.value.length; j++) {
        if (result.data[i].PROCESSOPERATIONNAME === defectCodes.value[j].enumvalue) {
          const codes = defectCodes.value[j].action;
          const arr = codes.split(',');
          // eslint-disable-next-line prefer-destructuring
          result.data[i].NGNAME1 = arr[0];
          // eslint-disable-next-line prefer-destructuring
          result.data[i].NGNAME2 = arr[1];
          // eslint-disable-next-line prefer-destructuring
          result.data[i].NGNAME3 = arr[2];
          // eslint-disable-next-line prefer-destructuring
          result.data[i].NGNAME4 = arr[3];
        }
      }
    }
    dailyOptions.data = result.data;
  }
};
</script>
